<?php
/**
 * Talents come from diligence, and knowledge is gained by accumulation.
 *
 * @author: 晋<657306123@qq.com>
 *
 */

namespace app\admin\controller\media;

use app\admin\Controller;
use think\Db;
use think\Request;
use Xin\Thinkphp5\Hint\Facade\Hint;
use Xin\Thinkphp5\Support\OS;

class ImageController extends Controller{

	/**
	 * 获取图片列表
	 *
	 * @param
	 * @return \think\response
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function index(){
		$data = Db::name("Picture")->where('uid', $this->user->getUserId())
			->order('id desc')
			->page($this->request->page(), $this->request->limit())
			->select();

		return Hint::result(array_map(function($item){
			if(strpos($item['path'], '/') === 0 && OS::getWebRootPath()){
				$item['path'] = OS::getWebRootPath()."/{$item['path']}";
			}
			return $item;
		}, $data));
	}

	/**
	 * 删除图片
	 *
	 * @param Request $request
	 * @return \think\response
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function delete(Request $request){
		$id = $request->param('id/d', 0, 'intval');
		if($id < 1) return Hint::error("invalid param id!", 400);

		$item = Db::name("Picture")->where('id', $id)->find();
		if(empty($item) || $item['uid'] != $this->user->getUserId()){
			//			return Ajax::error("图片不存在或已删除！", 400);
			return Hint::result([
				'id' => $id,
			]);
		}

		$data = Db::name("Picture")->where('id', $id)->delete();
		$file = '.'.$item['path'];
		if($data && is_file($file)) unlink($file);

		return Hint::result($data);
	}
}
